// pages/answer/answer.js
const qcloud = require('../../vendor/qcloud-weapp-client-sdk/index.js')
const config = require('../../config.js')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    offsetH:0,
    stateMachine:"", //判断结果是否返回
    clickState:"",
    radioVal: '', //单选和判断选中答案
    result: '', //对错返回值
    index: 0, //题目索引
    answerSerial: ['A', 'B', 'C', 'D', 'E', 'F', 'G'], //答案序号
    checkboxArray: [], //多选答案参数
    questionDTOs: [], //题目数据
    questionOptions: [],//题目列表
    judgeList: [{ "optionNo": "0", "content": "对" }, { "optionNo": "1", "content": "错" }], //判断题答案
    totalTime: 6, //总时间
    HalfTime: 3, // 总时间的一半
    timeIndex: 0, //倒计时计时器
    rotateVal: 0, // 旋转度
    times: '',
    resultQuestionVOsJn: [], //我方答案
    battleResultQuestionVOsJn:[], //应战者答案
    outscore: 0,// 我方总分
    realityScore:0, //应战总分
    machineScore:0, //机器人分数
    ownInfo:{}, //我方信息
    opponentInfo:{}, //应战着信息
    questionScore:10, //一题得分
    questionRightQuantity:0, //答对题数
    usedSeconds:0,//用时
    realityResultList:[],
    questionDTOsAnswer: '',
    matchType:"",
    realityParam:{},
    params:{},
    robotLevel:[
      { 'key':60,
        'value' :[0,20]
      },
      {
        'key': 70,
        'value': [20, 50]
      },
      {
        'key': 80,
        'value': [50, 100]
      },
      {
        'key': 90,
        'value': [100, 100000]
      }
    ],

    ownInfo: {},
    opponentInfo: {},
    userName: "澄邈、德泽、海超、海阳、海荣、海逸、海昌、瀚钰、瀚文、涵亮、涵煦、涵蓄、涵衍、浩皛、浩波、浩博、浩初、浩宕、浩歌、浩广、浩邈、浩气、浩思、浩言、鸿宝、鸿波、鸿博、鸿才、鸿畅、鸿畴、鸿达、鸿德、鸿飞、鸿风、鸿福、鸿光、鸿晖、鸿朗、鸿文、鸿轩、鸿煊、鸿骞、鸿远、鸿云、鸿哲、鸿祯、鸿志、鸿卓、嘉澍",
    animationData: {}
  },

  //倒计时结束显示当前正确答案
  setAnswer() {
    let questionDTOs = this.data.questionDTOs[this.data.index]
    let curType = questionDTOs.type;

    if (curType == 1) {
      let questionOptions = this.data.questionOptions
      let questionDTOs = this.data.questionDTOs[this.data.index]
      let rightAnswer = JSON.parse(questionDTOs.rightAnswer.replace(/(\d+)/g, '$1'))
      for (var i = 0; i < questionOptions.length; i++) {
        var optionNo = Number(questionOptions[i].optionNo)


        if (rightAnswer.indexOf(optionNo) > -1) {
          questionOptions[i].correct = true
        } else {
          questionOptions[i].correct = false
        }
      }

      this.setData({
        questionOptions: questionOptions
      })

    } else {
      this.setData({
        questionDTOsAnswer: questionDTOs.rightAnswer
      })
    }
  },

  onShow() {
    var animation = wx.createAnimation({
      duration: 600,
      timingFunction: 'ease',
    })


    this.animation = animation

    animation.translateX(0).step()

    this.setData({
      animationData: animation.export()
    })

    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          offsetH: res.windowHeight
        })
      }
    })
  },

  //倒计时
  countdown() {
    // //试卷信息
    // app.globalData.paperDTO = data.data.paperDTO

    let times;
    let questionDTOs = this.data.questionDTOs[this.data.index]
    let curType = questionDTOs.type;
    // let globalData = getApp().globalData
    let globalData = app.globalData.paperDTO

    let setTime = [globalData.limitSecondsSingle, globalData.limitSecondsMultiple, globalData.limitSecondsChecking]
    //0 单选 1 多选 2判断

    this.setData({
      totalTime: setTime[curType]
    })

    this.setData({
      HalfTime: this.data.totalTime / 2
    })

    this.setData({
      timeIndex: this.data.totalTime
    })

    this.setData({
      rotateVal: 360 / this.data.totalTime
    })

    if (this.data.matchType == 'reality') {
      
      
      this.statMachineFn().then((text) => {
        if (text == 'opponent_disconnect') {

          this.resultsFn('opponent_disconnect')

        } else if (text == 'transpond_question_result') {
          this.setData({
            stateMachine: text
          })
          this.nextQuestion()
        }
        
      })

      
    }

    
    
    

    this.setAnswer()

    this.data.times = setInterval(() => {
      this.setData({
        timeIndex: this.data.timeIndex - 1
      })

      if (this.data.timeIndex <= 0) {
        clearInterval(this.data.times)

        if (this.data.result !== true && this.data.result !== false) {
          this.setData({
            radioVal: 'no'
          })

          this.setData({
            result: false
          })
        }

        this.resultFn()
      }
    }, 1000)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取题目信息
    this.setData({
      questionDTOs: app.globalData.questionDTOs
    })

    // 获取是否人机还是对战
    this.setData({
      matchType: app.globalData.matchType
    })

    // 发起者信息
    this.setData({
      ownInfo: app.globalData.ownInfo
    })

    // 应战者信息
    this.setData({
      opponentInfo: app.globalData.opponentInfo
    })

    this.setData({
      questionOptions: this.data.questionDTOs[this.data.index].questionOptions.sort((a, b) => {
        return Math.random() > 0.5 ? 1 : -1;
      })
    })
  

    // 发起者信息
    this.setData({
      ownInfo: app.globalData.ownInfo
    })


    this.setData({
      opponentInfo: app.globalData.opponentInfo
    })
    
    this.countdown()
  },

  // 页面离开
  onUnload: function () {
    clearInterval(this.data.times)
  },

  onHide:function() {
    clearInterval(this.data.times)
    wx.closeSocket((res) => {
      console.log('WebSocket 已关闭！')
    })


    wx.navigateBack({})
  },

  onUnload:function() {
    clearInterval(this.data.times)
    wx.closeSocket((res) => {
      console.log('WebSocket 已关闭！')
    })

    // wx.redirectTo({
    //   url: `/pages/index/index`
    // })
  },

  // 结果提交
  resultsFn(type) {
    // 真人
    // outscore: 0,// 我方总分
    // realityScore:0, //应战总分
    // machineScore:0, //机器人分数
    // 用户一胜；2用户二胜；3平；
    let winnerResult

    if (type == 'opponent_disconnect') {
      winnerResult = 1
      app.globalData.gameScore = {
        userOne: this.data.outscore,
        // userTwo: this.data.machineScore
        userTwo: '离线'
      }

    } else {
      if (this.data.matchType == 'reality') {
        winnerResult = this.data.outscore == this.data.realityScore ? '3' : (this.data.outscore > this.data.realityScore ? 1 : 2)
        app.globalData.gameScore = {
          userOne: this.data.outscore,
          userTwo: this.data.realityScore
        }
      } else {
        winnerResult = this.data.outscore == this.data.machineScore ? '3' : (this.data.outscore > this.data.machineScore ? 1 : 2)
        app.globalData.gameScore = {
          userOne: this.data.outscore,
          userTwo: this.data.machineScore
        }
      }
    }

    

    let globalData = app.globalData.paperDTO

    this.data.resultQuestionVOsJn.forEach((v, i) => {
      if (!!v.answerCorrect) {
        this.setData({
          questionRightQuantity: this.data.questionRightQuantity + 1
        })
      }

      this.setData({
        usedSeconds: this.data.usedSeconds + v.usedSeconds
      })



      this.setData({
        totalUsedSeconds: this.data.totalUsedSeconds + v.limitSeconds
      })

    })

    let resultPaperVOJn = {
      "epId": globalData.epId, //试卷ID
      "type": globalData.type, //类型 0 模拟，1 正式 
      "name": globalData.name, //试卷名称 
      "questionQuantity": globalData.questionQuantity, //题目数量 
      "questionRightQuantity": this.data.questionRightQuantity, //答对题数
      "usedSeconds": this.data.usedSeconds,   //用时
      "score": this.data.questionScore * this.data.questionRightQuantity //得分
    }

    if (type == 'opponent_disconnect') {
      resultPaperVOJn['score'] = 0
    }

    let param = {
      "action": "submit_paper_result",
      "data": {
        "emId": app.globalData.emId,
        "resultPaperVOJn": JSON.stringify(resultPaperVOJn),
        "resultQuestionVOsJn": this.data.resultQuestionVOsJn,
        "winner": winnerResult
      }
    }

    this.setData({
      params: param
    })
    wx.sendSocketMessage({
      data: JSON.stringify(param)
    })

    // 人机情况下的操作
    if (this.data.matchType != 'reality') {
      app.globalData.examination = param
      
      if (app.globalData.answerType == '2') {
        wx.redirectTo({
          url: '/pages/contestsResult/contestsResult'
        })
      } else {
        wx.redirectTo({
          url: '/pages/officialResult/officialResult'
        })
      }

    } else {
      app.globalData.examination = param

      if (app.globalData.answerType == '2' ) {
        wx.redirectTo({
          url: '/pages/contestsResult/contestsResult'
        })
      } else {
        wx.redirectTo({
          url: '/pages/officialResult/officialResult'
        })
      }
    }
  },

  //初始化参数
  curParam() {
    clearInterval(this.data.times)
    if (this.data.index >= this.data.questionDTOs.length - 1) {
      this.resultsFn()
    } else {
      
      wx.onSocketMessage((data) => {
        var data = JSON.parse(data.data)
        // 提交结果返回
        if (data.action == 'submit_paper_result_rsp') {
          app.globalData.examination = this.data.params
          
          wx.redirectTo({
            url: '/pages/officialResult/officialResult'
          })
        }
      })

      this.setData({
        index: this.data.index + 1
      })

      this.setData({
        timeIndex: 0
      })

      this.setData({
        questionOptions: this.data.questionDTOs[this.data.index].questionOptions.sort((a, b) => {
          return Math.random() > 0.5 ? 1 : -1;
        })
      })


      this.setData({
        radioVal: ""
      })

      this.setData({
        result: ""
      })
      
      
      this.countdown()
    }
  },

  //存储答题数据
  resultFn() {
    let globalData = getApp().globalData
    let resultQuestionVOsJn = this.data.resultQuestionVOsJn
    
    let questionDTOs = this.data.questionDTOs[this.data.index]
    let setTime = [globalData.limitSecondsSingle, getApp().globalData.limitSecondsMultiple, getApp().globalData.limitSecondsChecking]
    let currentScore = ""

    resultQuestionVOsJn[this.data.index] = {
      'eqId': questionDTOs.eqId, //题目id
      'limitSeconds': setTime[questionDTOs.type], //限时
      'rightAnswer': questionDTOs.rightAnswer, // 正确答案
      'score': !!this.data.result ? 10 : 0, //得分
      'answerCorrect': this.data.result, //答题正确or错误
      'type': questionDTOs.type, //题目类型
      'usedSeconds': (this.data.totalTime - this.data.timeIndex) <= 0 ? 1 : (this.data.totalTime - this.data.timeIndex), //每题的时间
      'userAnswer': questionDTOs.type == 1 ? this.data.checkboxArray : this.data.radioVal //用户答案
    }

    
    this.setData({
      resultQuestionVOsJn: resultQuestionVOsJn
    })

    this.typeJudegment()
  },

  // 状态机
  statMachineFn() {
    return new Promise((resolve, reject)=>{
      let battleResultQuestionVOsJn = this.data.battleResultQuestionVOsJn
      wx.onSocketMessage((data) => {
        var data = JSON.parse(data.data)
        if (data.action == 'transpond_question_result') {
          battleResultQuestionVOsJn[this.data.index] = data.data.resultQuestionVOJn
          this.setData({
            realityScore: data.data.currentScore
          })
          resolve('transpond_question_result')
        } else if (data.action == 'opponent_disconnect' ) {
          resolve('opponent_disconnect')
        }
      })
    })
  },

  // 类型判断
  typeJudegment(){
    let battleResultQuestionVOsJn = this.data.battleResultQuestionVOsJn
    // outscore: 0,// 我方总分
    // realityScore: 0, //应战总分
    //   realityResultList:[],
    this.setData({
      outscore: this.data.resultQuestionVOsJn.filter((item) => {
        return !!item.answerCorrect === true
      }).length * 10
    })

    if (this.data.matchType == 'reality') {
      this.setData({
        "realityParam": {
          "action": "submit_question_result",  // 提交题目结果
          "data": {
            "resultQuestionVOJn": this.data.resultQuestionVOsJn[this.data.index],
            "currentQuestionNo": this.data.index, //当前第几题
            "currentScore": this.data.outscore
          }
        }
      })

      wx.sendSocketMessage({
        data: JSON.stringify(this.data.realityParam)
      })

      this.setData({
        clickState:true
      })

      this.nextQuestion()

    } else {
      let score = Math.round(Math.random() * 100)
      let level = this.data.robotLevel.filter((v) => {
        if (v.value[0] <= this.data.ownInfo.winCount && v.value[1] > this.data.ownInfo.winCount) {
          return v.key
        }
      })[0].key

      if (Math.floor(Math.random() * 100) <= level) {
        this.setData({
          realityResultList: this.data.realityResultList.concat(true)
        })

        this.setData({
          machineScore: this.data.realityResultList.length * 10
        })
      }
      
      clearInterval(this.data.times)
      setTimeout(() => {
        this.curParam()
      }, 2500)
    }

  },

  nextQuestion(state) {

    if (!!this.data.clickState && this.data.stateMachine == 'transpond_question_result') {
      this.setData({
        clickState:false
      })

      this.setData({
        stateMachine: ''
      })
      
      clearInterval(this.data.times)
      setTimeout(() => {
        this.curParam()
      }, 2500)
    }
    
  },

  //多选
  checkboxChange: function (e) {
    let checkArr = e.detail.value.map(Number);
    let questionOptions = this.data.questionOptions
    let questionDTOs = this.data.questionDTOs[this.data.index]
    let rightAnswer = JSON.parse(questionDTOs.rightAnswer).map(Number)

    this.setData({
      checkboxArray: e.detail.value
    })

    e.detail.value = []

    for (var i = 0; i < questionOptions.length; i++) {
      var optionNo = questionOptions[i].optionNo

      if (rightAnswer.indexOf(optionNo) > -1) {
        questionOptions[i].correct = true
      } else {
        questionOptions[i].correct = false
      }

      if (checkArr.indexOf(optionNo) > -1) {
        questionOptions[i].checked = true
      } else {
        questionOptions[i].checked = false
      }
    }

    this.setData({
      questionOptions: questionOptions
    })

    if (rightAnswer.length === this.data.checkboxArray.length) {
      this.setData({
        result: this.data.checkboxArray.sort().toString() == rightAnswer.sort().toString()
      })

      this.setData({
        radioVal: this.data.checkboxArray
      })

      this.resultFn()
    }

  },

  //单选
  radioChange(e) {
    let questionDTOs = this.data.questionDTOs[this.data.index]
    this.setData({
      radioVal: e.detail.value
    })


    e.detail.value = ''

    this.setData({
      result: questionDTOs.rightAnswer == this.data.radioVal
    })

    this.setData({
      questionDTOsAnswer: questionDTOs.rightAnswer
    })

    this.resultFn()

    

  },

  
  //应战模式
  reality() {

  },

  //人机随机
  manMachine() {

  }
})